<?php

namespace Home\Controller;
use Home\Org\Util\Sqlserver;
use Home\Org\Util\SQLSERVERDATASINGLETON;
/**
 * 品牌授权
 * @author dem
 *
 */
class AuthController  extends HomeController {
    
    /**
     * 
     * @see \Home\Controller\HomeController::index()
     */
    function index(){
        $this->display();
        
    }
    
    /**
     * ajax获取数据
     */
    function getIndexData(){
        $code  = I('code');
        $start = I('start');
        $end   = I('end');
        $type  = I('type');
        $key   = I('key'); //查询品牌
        $thecategory = I('thecategory'); //查询类目
        $thelevel = I('thelevel'); //查询级别
        
        $where = 'where 1=1 ';
        if($code){
            if($code == '*' || $code == '*_1' || $code == '*_2'){}
            else
            $where.= "  and code like '%{$code}%'";
        }
        
        if($key){
            //$where.=" and concat(brand_name,category,auth_chain) like '%{$key}%' ";
            $where.=" and brand_code = '{$key}' ";
        }

        if($thecategory){
            $where.=" and category like '%{$thecategory}%' ";
        }

        if($thelevel){
            $where.=" and level = '{$thelevel}' ";
        }
        
        if($start){
            $start = strtotime($start);
            $where.= " and  ctime>{$start}";
        }
        

        if($end){
            $end = strtotime($end);
            $where.= " and  ctime<{$end}";
        }
        
        if($type){
            $now = time();
            if($type==1){//未失效
                $where.= " and  end>{$now}";
            }else{//已失效
                $where.= " and  end<{$now}";
            }
        }// 0 全部， 1 未失效， 2 已失效。

        $model =$this->M2('Auth');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $countsql = "SELECT count(1) as total from  think_auth as a {$where} ";
        $limit = ' limit '.($pageIndex*$pageSize).','.$pageSize;
        $quersql = "SELECT * from  think_auth as a  {$where} order by a.id desc {$limit} ";
        $total = $model->query($countsql)[0]['total'];
        $res = $model->query($quersql);
        $newData = array();
        foreach ($res as $key=>$item){
            $res[$key]['status']=$this->getstatus($res[$key]['end']);
            $res[$key]['code'] = str_replace(',', '<br/>',  $res[$key]['code']);
            $res[$key]['cname'] = str_replace(',', '<br/>',  $res[$key]['cname']);
            $res[$key]['start']=date('Y-m-d', $res[$key]['start']);
            $res[$key]['end']=date('Y-m-d', $res[$key]['end']);
            $res[$key]['ctime']=date('Y-m-d', $res[$key]['ctime']);

            // 转换品类代码
            $plainCategories = array();
            $myCategories = $this->plainCategory($res[$key]['category'],$plainCategories);
            sort($myCategories);
            $categories = '';
            foreach ($myCategories as $inKey => $inValue)
            {
                $categories .= $inValue[text]." / ";
            }
            $res[$key]['category'] = $categories;

        }
        $data = array('total'=>$total,'data'=>$res);
        
        echo json_encode($data);
        exit;

    }

    /**
     * 导出授权
     */
    function exportIndexData(){
        $code  = I('code');
        $start = I('start');
        $end   = I('end');
        $type  = I('type');
        $key   = I('key'); //查询品牌
        $thecategory = I('thecategory'); //查询类目
        $thelevel = I('thelevel'); //查询级别

        $where = 'where 1=1 ';
        if($code){
            if($code == '*' || $code == '*_1' || $code == '*_2'){}
            else
                $where.= "  and code like '%{$code}%'";
        }

        if($key){
            //$where.=" and concat(brand_name,category,auth_chain) like '%{$key}%' ";
            $where.=" and brand_code = '{$key}' ";
        }

        if($thecategory){
            $where.=" and category like '%{$thecategory}%' ";
        }

        if($thelevel){
            $where.=" and level = '{$thelevel}' ";
        }

        if($start){
            $start = strtotime($start);
            $where.= " and  ctime>{$start}";
        }


        if($end){
            $end = strtotime($end);
            $where.= " and  ctime<{$end}";
        }

        if($type){
            $now = time();
            if($type==1){//未失效
                $where.= " and  end>{$now}";
            }else{//已失效
                $where.= " and  end<{$now}";
            }
        }// 0 全部， 1 未失效， 2 已失效。

        $model =$this->M2('Auth');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $countsql = "SELECT count(1) as total from  think_auth as a {$where} ";
        //$limit = ' limit '.($pageIndex*$pageSize).','.$pageSize;
        $quersql = "SELECT * from  think_auth as a  {$where} order by a.id desc "; //{$limit} ";
        $total = $model->query($countsql)[0]['total'];
        $res = $model->query($quersql);
        $newData = array();
        foreach ($res as $key=>$item){
            $res[$key]['status']=$this->getstatus($res[$key]['end']);
            $res[$key]['code'] = str_replace(',', '<br/>',  $res[$key]['code']);
            $res[$key]['cname'] = str_replace(',', '<br/>',  $res[$key]['cname']);
            $res[$key]['start']=date('Y-m-d', $res[$key]['start']);
            $res[$key]['end']=date('Y-m-d', $res[$key]['end']);
            $res[$key]['ctime']=date('Y-m-d', $res[$key]['ctime']);

            // 转换品类代码
            $plainCategories = array();
            $myCategories = $this->plainCategory($res[$key]['category'],$plainCategories);
            sort($myCategories);
            $categories = '';
            foreach ($myCategories as $inKey => $inValue)
            {
                $categories .= $inValue[text]." / ";
            }
            $res[$key]['category'] = $categories;

        }
        //$data = array('total'=>$total,'data'=>$res);
        //echo json_encode($data);
        //var_dump($res);

        $data = $res;

        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '平台代码');
        $currentSheet->setCellValue('B'.$m, '平台名称');
        $currentSheet->setCellValue('C'.$m, '平台类目');
        $currentSheet->setCellValue('D'.$m, '品牌');
        $currentSheet->setCellValue('E'.$m, '授权级别');
        $currentSheet->setCellValue('F'.$m, '授权链');
        $currentSheet->setCellValue('G'.$m, '状态');
        $currentSheet->setCellValue('H'.$m, '授权开始时间');
        $currentSheet->setCellValue('I'.$m, '授权结束时间');
        $currentSheet->setCellValue('J'.$m, '添加时间');
        $currentSheet->setCellValue('K'.$m, '备注');
        $currentSheet->setCellValue('L'.$m, '审核状态');

        $cellIndex = 1;
        foreach ($data as $key => $value){

            $cellIndex++;

            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['code'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['cname'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C'.$cellIndex,$value['categorytxt'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D'.$cellIndex,$value['brand_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E'.$cellIndex,$value['level'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('F'.$cellIndex,$value['auth_chain'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G'.$cellIndex,$value['status'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H'.$cellIndex,$value['start'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I'.$cellIndex,$value['end'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J'.$cellIndex,$value['ctime'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('K'.$cellIndex,$value['note'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L'.$cellIndex,$value['examine_status'], \PHPExcel_Cell_DataType::TYPE_STRING);

        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

        exit;
    }
    
    function getstatus($end){
        $return = "<span style='color:green'>正常</span>";
        if($end<time()){
            $return = "<span style='color:red'>失效</span>";
        }
        return $return;
    }
    /**
     * 添加  修改
     * @see \Home\Controller\HomeController::save()
     */
    function save(){
        $id = I('id');
        if($id){
            $model = $this->M2('Auth');
            $data = $model->where("id={$id}")->find();
            $attarr = explode(';', $data['attachment']);//附件
         
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $attlist[$key]=$filemodel->where("id={$file_id}")->find();
                $attlist[$key]['code']=$att;
                $attlist[$key]['size']= ceil($attlist[$key]['size']/1000);
            }
            $data['start']=date('Y-m-d', $data['start']);
            $data['end']=date('Y-m-d', $data['end']);
            $data['auth_chain'] = explode('->',  $data['auth_chain']);
            $data['att']=$attlist;

            // for category
            $categories = explode(",", $data['category']);
            $this->assign('firstCategory',$categories[0]);
            $this->assign('data',$data);

            //check permission
            if ($this->checkPermission()){
                // has permission,go progress then.
                $this->assign('haspermission',TRUE);
            }else{
                // has not permission.
                $this->assign('haspermission',FALSE);
            }

        }
        if(I('splid'))
        $this->assign('slp',array('id'=>I('splid'),'name'=>I('splname')));
        else 
        $this->assign('slp',array('id'=>$data['spl_id'],'name'=>$data['spl_name']));
        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $plugin['auth'] = true;
        $this->assign('filepath','/Uploads/Download/auth/'.date('Y-m').'/');
        $this -> assign("plugin", $plugin);
        $this->display();
        
    }
    
    function dosave(){
        $data = json_decode(I('data'),1);
      
        $model = $this->M2('Auth');
      
        $data['start'] = strtotime($data['start']);
        $data['end'] = strtotime($data['end']);
       
        $autharr = $data['auth_chain'];
        unset( $data['auth_chain']);
        foreach ($autharr as $authstr){
           
            $data['auth_chain'].=$authstr.'->';

        }  
   
        $data['auth_chain'] = rtrim( $data['auth_chain'],'->');

        // 根据授权链算LEVEL-旧的
        //$data['level'] = count($autharr);
        $data['examine_status'] = 0;
       
        if($data['id']){
            // update

            // 谁创建 则 只能 谁修改
            $authID = session('auth_id');
            $check = $model->where('id='.$data['id'])->find();
            if ($check['operatorid'] == $authID) {
                $data['status'] = 'U';
                echo $model->where("id={$data['id']}")->save($data);

                //2017-08-18 修改时添加备注
                $remarkes = $data['remarkes'];
                $info = "发起申请";
                $info = $remarkes?$info.",备注:".$remarkes:$info;
                $logModel =M('SapAuthLog');
                $logModel->add(array('pid'=>$data['id'],'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

            }
        }else{
            // add

            // 标记状态
            $data['status']  = 'A';

            // 绑定用户
            $data['operatorid'] = session('auth_id');
            $data['operatorname'] = session('emp_no');
            $data['user']=session('emp_no');

            $data['ctime']=time();

            echo $res = $model->add($data);

            //2017-08-18 创建时添加备注
            $remarkes = $data['remarkes'];
            $info = "发起申请";
            $info = $remarkes?$info.",备注:".$remarkes:$info;
            $logModel =M('SapAuthLog');
            $logModel->add(array('pid'=>$res,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

        }

        //TODO: 发送邮件微信
        //$receiver = "maxwell.shi";
        // 2017-08-23 将 mario 的权限 移交给 wendy.li
        $receiver = "wendy.li";
        $operator = session('emp_no');
        $this->sendEmail($receiver.'@g-town.com.cn', "品牌:{$data['brand_name']},授权信息变更", "品牌:{$data['brand_name']},授权信息变更<br/>操作人:{$operator}");
        //weixinsendmsg("品牌:{$data['brand_name']},授权信息变更", "品牌:{$data['brand_name']},授权信息变更\n操作人:{$operator}",$operator);

        // 只有当 examine_status 的值不等于1时,更新状态。
        $sapSupplierModel = M('SapSupplier');
        $supplierItem = $sapSupplierModel->where("id={$data['spl_id']}")->find();
        if ($supplierItem['examine_status'] != 1) {
            $sapSupplierModel->where("id={$data['spl_id']}")->save(array('examine_status' => 0));
        }

        exit;
        
    }
    
    function upload() {
        $this -> _upload();
    }
    
    
    protected function _upload() {
        if (C('CHUNK_UPLOAD')) {
            $files = $this -> _chunk_upload();
        } else {
            $files = $_FILES;
        }
    
        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');
        /* 调用文件上传组件上传文件 */
        $File = D('File');
        $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
        $info = $File -> upload($files, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
    
        /* 记录附件信息 */
        if ($info) {
            if (!empty($info['file'])) {
                $return = $info['file'];
            }
            if (!empty($info['imgFile'])) {
                $return = $info['imgFile'];
                $return['url'] = $return['path'];
            }
            $return['sid'] = think_encrypt($info['file']['id']);
            $return['status'] = 1;
            $return['error'] = 0;
        } else {
            $return['status'] = 0;
            $return['info'] = $File -> getError();
        }
        /* 返回JSON数据 */
        $this -> ajaxReturn($return);
    }
    
    function down(){
        $id = I('id');
        if($id){
            $filename = "att_{$id}.zip";
            $file = WWWROOT.'/Uploads/Download/auth/'.date('Y-m').'/';
            if(!file_exists($file)){
                mkdir($file);
            }
            if(file_exists($file.$filename)){
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                readfile($file.$filename);
            }
            $model = $this->M2('Auth');
            $data = $model->where("id={$id}")->find();
            $attarr = explode(';', $data['attachment']);//附件
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $file_=$filemodel->where("id={$file_id}")->find();
                $attlist[]=WWWROOT.'/Uploads/Download/'.$file_['savepath'].$file_['savename'];
            }
            
             $this->zip($file.$filename,$attlist);
           
             header('Content-Disposition: attachment; filename="' . $filename . '"');
             readfile($file.$filename);
        }
        
    }
    
    /**
     * 
     * @param unknown $tableName
     */
    function M2($tableName){
        return  M($tableName);
        //return  M($tableName,'mallbuilder_','DB_CONFIG2');
    }
    
    
    /**
     * 压缩文件
     * @param string $filename
     * @param unknown $files
     * @return boolean|unknown
     */
    function zip($filename ='',$files=array()){
        $zip = new \ZipArchive();
        if ($zip->open($filename, \ZipArchive::CREATE)!==TRUE) {
            echo  'zip create error';
               exit;
        }
        foreach ($files as $file){
        if(file_exists($file)){
               
                $zip->addFile($file,basename($file));
            }
            
            //$zip->addFile( $files, basename($files));//第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
         
        $res = $zip->numFiles;
        $zip->close();
    
        return $res;
    }
    
    
    /**
     * 下载选中的
     */
    function  dwonSelected(){
        $ids = rtrim(I('ids'),',');
        $model = $this->M2('auth');
        $list  = $model->where("id in({$ids})")->select();
        $file = WWWROOT.'/Uploads/Download/ziptemp/';//.date('Ymdhis').'/';
        $authpath =  WWWROOT.'/Uploads/Download/';//.date('Ymdhis').'/';
        $zipname = date('Ymdhis').'.zip';
        if(!file_exists($file)){
            mkdir($file);
        }
        $zip=new \ZipArchive();
        $filem = M('file');
            if($zip->open($file.$zipname, \ZipArchive::OVERWRITE)=== TRUE){
                foreach ($list as $vo){
                     $name =   iconv("utf-8//IGNORE","gb2312",$vo['name']);
                     $zip->addEmptyDir($name);
                      $attachment = explode(';', $vo['attachment']);
                      foreach ($attachment as $att){
                          if(!$att)continue;
                          $file_id = think_decrypt($att);
                          $attmsg = $filem->where("id={$file_id}")->find();
                          $tempfile = $authpath.$attmsg['savepath'].$attmsg['savename'];
                          $zip->addFile($tempfile,$name.'/'.basename($tempfile));
                      }
                    
                }
                $zip->close(); //关闭处理的zip文件
            }   
        
  
            header('Content-Disposition: attachment; filename="' . '附件.zip' . '"');
            readfile($file.$zipname);
      
        
      
        
    }
    
    function select(){
      
        $this->display();
    }
    /**
     * 选择平台
     */
    function getSelectData(){
        $key = I('key');
        require 'Application/Home/ORG/Util/Sqlserver.class.php';
        $sql=  "select U_Cardcode  ,U_CardName from [@ti_Z0070] where U_Status='1' and U_Cardcode like '%{$key}%' union all select U_Cardcode  ,U_CardName from [@ti_Z0070] where U_Status='1' and U_CardName like '%{$key}%'";
       if(!$key){
           $sql=  "select U_Cardcode  ,U_CardName from [@ti_Z0070] where U_Status='1' ";
            
       }
        $sql= iconv("utf-8","gb2312",$sql);
        $db = new Sqlserver();
        $db->connent();
        $data = $db->query($sql);
        if($key){
            $array = array();
            $temp = array(array('U_Cardcode'=>'*','U_CardName'=>'所有平台'),array('U_Cardcode'=>'*_1','U_CardName'=>'所有积分类平台'),array('U_Cardcode'=>'*_2','U_CardName'=>'所有分期类平台'));
            foreach ($temp as $index=>$vo){
              
                if(strstr($temp[$index]['U_Cardcode'].$temp[$index]['U_CardName'],$key)){
                    array_push($array,$vo);
                }
            }
   
            
        }else 
        $array= array(array('U_Cardcode'=>'*','U_CardName'=>'所有平台'),array('U_Cardcode'=>'*_1','U_CardName'=>'所有积分类平台'),array('U_Cardcode'=>'*_2','U_CardName'=>'所有分期类平台'));
        foreach ($data  as $item){
            array_push($array, $item);
        }
        
        
        $data = array('total'=>count($data),'data'=>$array);
        echo    json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    
    
    function selectauth(){
        $this->display();
    }

    function plainCategory($key,$result)
    {
        import("@.ORG.Util.SQLSERVERDATASINGLETON");
        $sqlSERVERDATASINGLETON  = SQLSERVERDATASINGLETON::getInstance();
        $categories = $sqlSERVERDATASINGLETON->getDataTIZ0151();

        foreach ($categories as $inkey => $value){

            if($value['id'] == $key)
            {
                //var_dump($value);die();
                if ($value['pid'])
                {
                    // continue
                    $result[] = $value;
                    return $this->plainCategory($value['pid'],$result);
                }else{
                    $result[] = $value;
                    return $result;
                }
            }

        }

    }

    private function checkPermission(){

        //get operator by db
        $modelSupplierOperator = D("supplier_operator");
        $filed = ('*');
        $operatorList = $modelSupplierOperator->field($filed)->select();
        foreach ($operatorList as $key => $value){
            $userlist[] = $value['emp_no'];
            $operator[$value['emp_no']] = $value['type'];
        }
        $this->userlist = $userlist;

        $user = session('user_name');
        if (in_array($user, $this->userlist))
        {
            //权限类型，默认0发起人，1审批人
            if ($operator[$user] == 1)
            {
                // 确认是审核人
                return TRUE;
            }
            return FALSE;
        }
        return FALSE;
    }

    public function review20170706(){

        //供应商ID
        $a_id   = intval(I('id'));
        //审批类型
        $status = intval(I('status'));
        //审批记录表
        $logModel =M('SapAuthLog');

        //供应商表
        $authModel = M('Auth');
        //更新供应商状态
        $authModel->where("id={$a_id}")->save(array('examine_status'=>$status));

        //记录审批历史
        $remarkes = I('remarkes');
        if ($status == 0){
            $info = "发起申请";
        }else {
            $info = $status == 1 ? "审核通过" : "审核未通过";
        }
        $info = $remarkes?$info.",备注:".$remarkes:$info;
        $logModel->add(array('pid'=>$a_id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

        //返回数据
        echo 1;exit;
    }

    function getlog(){
        $s_id   = intval(I('id'));
        $logModel =M('SapAuthLog');
        $data = $logModel->where("pid={$s_id}")->order("id desc")->select();
        echo json_encode($data);
        exit;
    }
    

    
}